# -*- coding: utf-8 -*-
"""
管理员文件管理模块
包含用户文件查看、删除、存储配额管理等功能
@api-version: 1.0.0
REF: API-ADMIN-008~011
"""

from flask import request
from backend.models.user import User
from backend.models.virtual_file import VirtualFile
from backend.models.user_storage_quota import UserStorageQuota
from backend.services.virtual_netdisk_service import VirtualNetdiskService
from backend.utils.response import success_response, error_response, not_found_response
from backend.utils.auth import admin_required
from backend.models import db
from . import admin_bp


@admin_bp.route('/admin/users/<int:user_id>/files', methods=['GET'])
@admin_required
def get_user_files(user_id):
    """获取指定用户的文件列表
    REF: API-ADMIN-008
    """
    try:
        # 检查用户是否存在
        user = User.query.get(user_id)
        if not user:
            return not_found_response('用户不存在')
        
        # 获取查询参数
        parent_id = request.args.get('parent_id', type=int)
        page = request.args.get('page', 1, type=int)
        page_size = min(request.args.get('page_size', 20, type=int), 100)
        search = request.args.get('search', '').strip()
        file_type = request.args.get('file_type', '').strip()  # folder/file
        sort_by = request.args.get('sort_by', 'created_at')
        sort_order = request.args.get('sort_order', 'desc')
        
        # 构建查询
        query = VirtualFile.query.filter_by(owner_id=user_id)
        
        # 父目录筛选
        if parent_id is not None:
            query = query.filter_by(parent_id=parent_id)
        else:
            # 默认显示根目录
            query = query.filter_by(parent_id=None)
        
        # 搜索条件
        if search:
            query = query.filter(VirtualFile.name.like(f'%{search}%'))
        
        # 文件类型筛选
        if file_type == 'folder':
            query = query.filter_by(is_folder=True)
        elif file_type == 'file':
            query = query.filter_by(is_folder=False)
        
        # 排序
        if sort_by == 'name':
            order_field = VirtualFile.name
        elif sort_by == 'size':
            order_field = VirtualFile.file_size
        elif sort_by == 'updated_at':
            order_field = VirtualFile.updated_at
        else:
            order_field = VirtualFile.created_at
        
        if sort_order == 'desc':
            query = query.order_by(order_field.desc())
        else:
            query = query.order_by(order_field.asc())
        
        # 分页
        pagination = query.paginate(
            page=page, per_page=page_size, error_out=False
        )
        
        # 转换数据格式
        files_data = []
        for file_item in pagination.items:
            file_dict = {
                'id': file_item.id,
                'name': file_item.name,
                'parent_id': file_item.parent_id,
                'is_folder': file_item.is_folder,
                'file_size': file_item.file_size,
                'storage_file_id': file_item.storage_file_id,
                'is_favorite': file_item.is_favorite,
                'is_hidden': file_item.is_hidden,
                'access_count': file_item.access_count,
                'last_access_time': file_item.last_access_time.isoformat() if file_item.last_access_time else None,
                'created_at': file_item.created_at.isoformat(),
                'updated_at': file_item.updated_at.isoformat(),
                'full_path': file_item.get_full_path()
            }
            files_data.append(file_dict)
        
        # 获取用户存储信息
        storage_quota = UserStorageQuota.query.filter_by(user_id=user_id).first()
        storage_info = {
            'quota_limit': storage_quota.quota_limit if storage_quota else 0,
            'used_space': storage_quota.used_space if storage_quota else 0,
            'file_count': storage_quota.file_count if storage_quota else 0,
            'folder_count': storage_quota.folder_count if storage_quota else 0
        }
        
        return success_response(
            data={
                'user': {
                    'id': user.id,
                    'nickname': user.nickname,
                    'email': user.email
                },
                'storage_info': storage_info,
                'files': {
                    'items': files_data,
                    'total': pagination.total,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': pagination.pages
                }
            },
            message='获取用户文件列表成功'
        )
        
    except Exception as e:
        return error_response('获取用户文件列表失败', 500)


@admin_bp.route('/admin/users/<int:user_id>/files/<int:file_id>', methods=['DELETE'])
@admin_required
def delete_user_file(user_id, file_id):
    """删除指定用户的文件
    REF: API-ADMIN-009
    """
    try:
        # 检查用户是否存在
        user = User.query.get(user_id)
        if not user:
            return not_found_response('用户不存在')
        
        # 检查文件是否存在且属于该用户
        file_item = VirtualFile.query.filter_by(id=file_id, owner_id=user_id).first()
        if not file_item:
            return not_found_response('文件不存在')
        
        # 使用虚拟网盘服务删除文件
        service = VirtualNetdiskService()
        result = service.delete_files([file_id], user_id)
        
        if result['success']:
            return success_response(
                data={
                    'deleted_file': {
                        'id': file_id,
                        'name': file_item.name,
                        'is_folder': file_item.is_folder
                    },
                    'storage_reclaimed': result.get('storage_reclaimed', 0)
                },
                message='文件删除成功'
            )
        else:
            return error_response(result.get('message', '文件删除失败'), 500)
        
    except Exception as e:
        return error_response('文件删除失败', 500)


@admin_bp.route('/admin/users/<int:user_id>/storage', methods=['GET'])
@admin_required
def get_user_storage_info(user_id):
    """获取用户存储信息
    REF: API-ADMIN-010
    """
    try:
        # 检查用户是否存在
        user = User.query.get(user_id)
        if not user:
            return not_found_response('用户不存在')
        
        # 获取存储配额信息
        storage_quota = UserStorageQuota.query.filter_by(user_id=user_id).first()
        
        # 统计文件信息
        total_files = VirtualFile.query.filter_by(owner_id=user_id, is_folder=False).count()
        total_folders = VirtualFile.query.filter_by(owner_id=user_id, is_folder=True).count()
        
        # 计算使用率
        quota_limit = storage_quota.quota_limit if storage_quota else 0
        used_space = storage_quota.used_space if storage_quota else 0
        usage_rate = (used_space / quota_limit * 100) if quota_limit > 0 else 0
        
        return success_response(
            data={
                'user': {
                    'id': user.id,
                    'nickname': user.nickname,
                    'email': user.email
                },
                'storage': {
                    'quota_limit': quota_limit,
                    'used_space': used_space,
                    'available_space': max(0, quota_limit - used_space),
                    'usage_rate': round(usage_rate, 2),
                    'file_count': total_files,
                    'folder_count': total_folders,
                    'last_calculated_at': storage_quota.last_calculated_at.isoformat() if storage_quota and storage_quota.last_calculated_at else None
                }
            },
            message='获取用户存储信息成功'
        )
        
    except Exception as e:
        return error_response('获取用户存储信息失败', 500)


@admin_bp.route('/admin/users/<int:user_id>/storage/quota', methods=['PUT'])
@admin_required
def update_user_storage_quota(user_id):
    """更新用户存储配额
    REF: API-ADMIN-011
    """
    try:
        # 检查用户是否存在
        user = User.query.get(user_id)
        if not user:
            return not_found_response('用户不存在')
        
        data = request.get_json() or {}
        new_quota = data.get('quota_limit')
        
        if not new_quota or not isinstance(new_quota, int) or new_quota < 0:
            return error_response('配额限制必须是非负整数', 400)
        
        # 获取或创建配额记录
        storage_quota = UserStorageQuota.query.filter_by(user_id=user_id).first()
        if not storage_quota:
            storage_quota = UserStorageQuota(
                user_id=user_id,
                quota_limit=new_quota,
                used_space=0,
                file_count=0,
                folder_count=0
            )
            db.session.add(storage_quota)
        else:
            storage_quota.quota_limit = new_quota
        
        db.session.commit()
        
        return success_response(
            data={
                'user_id': user_id,
                'quota_limit': new_quota,
                'used_space': storage_quota.used_space
            },
            message='用户存储配额更新成功'
        )
        
    except Exception as e:
        return error_response('用户存储配额更新失败', 500)